package com.web.hilover.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Slf4j
public class FileUtil {
    private static final String[] ALLOWED_IMAGE_EXTENSIONS = {".jpg", ".jpeg", ".png", ".gif", ".bmp"};
    private static final String UPLOAD_DIR = "uploads";
    
    public static String saveImage(MultipartFile file, String type) throws IOException {
        String originalFilename = file.getOriginalFilename();
        // 检查文件扩展名是否为允许的图片格式
        if (!isImageFile(originalFilename)) {
            throw new IllegalArgumentException("上传的文件不是有效的图片格式");
        }
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String filename = UUID.randomUUID().toString() + extension;
        
        String relativePath = "/" + type + "/" + filename;
        String absolutePath = new File(UPLOAD_DIR + relativePath).getAbsolutePath();
        
        File targetFile = new File(absolutePath);
        if (!targetFile.getParentFile().exists()) {
            targetFile.getParentFile().mkdirs();
        }
        
        file.transferTo(targetFile);
        return relativePath;
    }
    //限制图片
    private static boolean isImageFile(String filename) {
        if (filename == null) {
            return false;
        }
        String extension = filename.substring(filename.lastIndexOf("."));
        for (String allowedExtension : ALLOWED_IMAGE_EXTENSIONS) {
            if (extension.equalsIgnoreCase(allowedExtension)) {
                return true;
            }
        }
        return false;
    }
} 